package qeug.shsh.facde.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.drew.lang.annotations.NotNull;
import com.huawei.shade.org.apache.commons.logging.Log;
import com.huawei.shade.org.apache.commons.logging.LogFactory;
import kd.bos.data.BusinessDataReader;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.metadata.IDataEntityType;
import kd.bos.dataentity.metadata.dynamicobject.DynamicObjectType;
import kd.bos.entity.EntityMetadataCache;
import kd.bos.entity.MainEntityType;
import kd.bos.entity.botp.runtime.ConvertOperationResult;
import kd.bos.entity.botp.runtime.PushArgs;
import kd.bos.entity.botp.runtime.SourceBillReport;
import kd.bos.entity.datamodel.IRefrencedataProvider;
import kd.bos.entity.datamodel.ListSelectedRow;
import kd.bos.entity.operate.OperateOptionConst;
import kd.bos.entity.operate.result.IOperateInfo;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.exception.KDBizException;
import kd.bos.openapi.common.custom.annotation.*;
import kd.bos.openapi.common.result.CustomApiResult;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.botp.BFTrackerServiceHelper;
import kd.bos.servicehelper.botp.ConvertServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import qeug.shsh.facde.info.PaymentModel;
import qeug.shsh.facde.resultext.PaymentResultExt;
import qeug.shsh.helper.FacadeHelper;

import java.io.Serializable;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * &#064;description：付款单接口
 * 说明：回传单据：差旅报销单，借款单，费用报销单，付款申请单
 */
@ApiController(value = "SavePaymentOrderController", desc = "金蝶付的款接口，自定义插件")
public class SavePaymentOrderController implements Serializable {

    private final static Log logger = LogFactory.getLog(SavePaymentOrderController.class);//日志

    private static String oBill = "";//源单标识

    static CustomApiResult auditApiResultExt = new CustomApiResult();

    @ApiPostMapping(value = "/shsh_paymentOrder", desc = "付款单api接口")
    public CustomApiResult<@ApiResponseBody("返回参数") PaymentResultExt> resultExt
            (@NotNull @ApiRequestBody(value = "入参") PaymentModel model) {

        auditApiResultExt.setStatus(true);
        OperateOption operateOption = OperateOption.create();
        operateOption.setVariableValue("ignoreValidation", String.valueOf(true));//绕过网络互斥操作

//        HashMap<String, Object> auditLog = new HashMap<>();//记录付款结果日志
        int execDate = model.getExecDate();//实际付款日期
        String cashAmount = model.getCashamount();//银行存款
        String billAmount = model.getBillamount();//票据
        String totalMoney = model.getTotalMoney();//总金额
        String lcAmount = model.getLcamount();//信用证
        String sn = model.getSn();//单据号
        String state = model.getState();//状态
        String bankNum = model.getBankNum();//付款账号
        String referenceCode = model.getReferenceCode();//参考码

        // 实际付款日期
        Date bizDate = null;
        if (execDate != 0) {
            String execDate1 = String.valueOf(execDate);//实际付款日期
            SimpleDateFormat inputFormat = new SimpleDateFormat("yyyyMMdd");
            try {
                bizDate = inputFormat.parse(execDate1); // 解析为 Date 对象
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }

        DynamicObject Bill = getBillType(sn);//获取单据数据
        Bill.set("qeug_referencecode", referenceCode); // 参考码

        //校验推送信息中的总金额是否大于收款金额；大于收款金额的推送失败
        DynamicObjectCollection accountEntryCollection = Bill.getDynamicObjectCollection("accountentry");//收款信息分录
        DynamicObject accountEntry = accountEntryCollection.get(0);
        BigDecimal oriReceiveAmount = accountEntry.getBigDecimal("orireceiveamount");//收款金额
        BigDecimal oriaccnotpayamount = accountEntry.getBigDecimal("oriaccnotpayamount");//未付金额
        BigDecimal oriaccpayedamount = accountEntry.getBigDecimal("oriaccpayedamount");//已付金额
        BigDecimal totalMoneyBD = new BigDecimal(totalMoney).abs();//总金额绝对值
        if (oriReceiveAmount == null || oriaccnotpayamount.compareTo(totalMoneyBD) < 0) {
            //总金额大于未付金额，推送失败
            auditApiResultExt.setStatus(false);
            auditApiResultExt.setMessage(sn + "推送失败，推送金额大于当前单据未付金额");
            return auditApiResultExt;
        }

        DynamicObjectCollection qeug_entryentity = Bill.getDynamicObjectCollection("qeug_entryentity");//付款结果回传分录
        DynamicObjectType type = qeug_entryentity.getDynamicObjectType();
        DynamicObject entry = new DynamicObject(type);
        entry.set("qeug_currencyfield", BusinessDataServiceHelper.loadSingle("bd_currency", new QFilter[]{
                new QFilter("number", QCP.equals, "CNY")}));//默认人民币

        if (oBill.equals("er_tripreimbursebill") || oBill.equals("er_dailyreimbursebill") || oBill.equals("er_dailyloanbill")) {
            //差旅报销单，费用报销单，借款单传入付款账号值
            logger.info(sn + "传入付款账号和会计科目" + bankNum);
            QFilter[] a = new QFilter[]{new QFilter("bankaccountnumber", "=", bankNum)};//银行账号
            DynamicObject am_accountbank = BusinessDataServiceHelper.loadSingle("am_accountbank", a);//账户查询单据
            if (am_accountbank != null) {
                entry.set("qeug_bank_acc_salary", am_accountbank);//付款账号
                Bill.set("qeug_bank_acc_salary1", am_accountbank);//表头付款账号
                DynamicObject qeug_account = am_accountbank.getDynamicObject("qeug_account");//会计科目
                if (qeug_account != null) {
                    String number = qeug_account.getString("number");
                    QFilter[] a1 = new QFilter[]{new QFilter("number", "=", number)};
                    DynamicObject bd_accountview = BusinessDataServiceHelper.loadSingle("bd_accountview", a1);//会计科目
                    entry.set("qeug_acct_ppe", bd_accountview);//会计科目
                    Bill.set("qeug_acct_ppe1", bd_accountview);//表头会计科目
                }
            }
        }

        if ("1".equals(state)) {
            //付款成功
            if (oriaccnotpayamount.compareTo(totalMoneyBD) != 0) {
                //总金额小于未付金额，推送成功，只记录付款信息，待之后付款
                entry.set("qeug_state", state);//付款类型
                entry.set("qeug_paydates", bizDate);//付款日期
                entry.set("qeug_payamount", totalMoney);//付款金额
                qeug_entryentity.add(entry);//付款结果回传记录分录
                accountEntry.set("oriaccpayedamount", totalMoneyBD.add(oriaccpayedamount));//已付金额
                BigDecimal oriaccnotpayAmount = oriReceiveAmount.subtract(totalMoneyBD.add(oriaccpayedamount));//收款金额减去付款金额
                accountEntry.set("oriaccnotpayamount", oriaccnotpayAmount);//未付金额
                SaveServiceHelper.saveOperate(oBill, new DynamicObject[]{Bill}, OperateOption.create());
                auditApiResultExt.setMessage("推送成功！");
                return auditApiResultExt;
            }

            //付款成功，已全部付款，将单据状态改为已付款并且扣减预算和生成凭证
            entry.set("qeug_state", state);//付款类型
            entry.set("qeug_paydates", bizDate);//付款日期
            entry.set("qeug_payamount", totalMoney);//付款金额
            qeug_entryentity.add(entry);//付款结果回传记录分录
            accountEntry.set("oriaccpayedamount", totalMoneyBD.add(oriaccpayedamount));//已付金额
            BigDecimal oriaccnotpayAmount = oriReceiveAmount.subtract(totalMoneyBD.add(oriaccpayedamount));//收款金额减去付款金额
            accountEntry.set("oriaccnotpayamount", oriaccnotpayAmount);//未付金额

            if (oBill.equals("er_tripreimbursebill") || oBill.equals("er_dailyreimbursebill") || oBill.equals("er_dailyloanbill")) {
                //借款单，差旅报销单，费用报销单付款日期赋值，需要生成凭证使用（除去付款申请，付款申请在调用推送G6时给付款日期赋值
                Bill.set("head_paydate", bizDate);//付款日期
            }

            //付款成功，已全部付款，将单据状态改为已付款
            if (oBill.equals("er_dailyloanbill")) {
                //借款单：需要单独使用状态转换操作才能使得单据状态变为已付款
                SaveServiceHelper.saveOperate(oBill, new DynamicObject[]{Bill}, OperateOption.create());
                SaveServiceHelper.saveOperate("statusconvert", oBill, new DynamicObject[]{Bill}, operateOption);//调用状态转换操作
            } else {
                //其他单据可直接赋值使得单据状态变为已付款
                Bill.set("billstatus", "G");
                SaveServiceHelper.saveOperate(oBill, new DynamicObject[]{Bill}, OperateOption.create());
            }

            //扣减预算和生成凭证操作
            String id1 = String.valueOf(Bill.get("id"));
            switch (oBill) {
                case "er_tripreimbursebill": {
                    //差旅报销单
                    logger.info("差旅报销单调用扣减预算和生成凭证操作");
                    OperationResult operationResult = SaveServiceHelper.saveOperate("dobuget", "er_tripreimbursebill", new DynamicObject[]{Bill}, operateOption);//调用扣减预算操作
                    boolean success = operationResult.isSuccess();
                    if (success) {
                        OperationServiceHelper.executeOperate("generatevoucher", "er_tripreimbursebill", new Object[]{id1}, operateOption);//调用生成凭证操作
                    }
                    break;
                }
                case "er_dailyreimbursebill": {
                    //费用报销单
                    logger.info("费用报销单调用扣减预算和生成凭证操作");
                    OperationResult operationResult = SaveServiceHelper.saveOperate("dobuget", "er_dailyreimbursebill", new DynamicObject[]{Bill}, operateOption);//调用扣减预算操作
                    boolean success = operationResult.isSuccess();
                    if (success) {
                        OperationServiceHelper.executeOperate("generatevoucher", "er_dailyreimbursebill", new Object[]{id1}, operateOption);//调用生成凭证操作
                    }
                    break;
                }
                case "er_dailyloanbill":
                    //借款单
                    logger.info("借款单调用生成凭证操作");
                    OperationServiceHelper.executeOperate("generatevoucher", "er_dailyloanbill", new Object[]{id1}, operateOption);//调用生成凭证操作
                    break;
            }
        } else if ("2".equals(state) || "3".equals(state)) {
            //2、终止付款和冲销付款
            //终止付款和冲销付款，将单据状态改为关闭
            Bill.set("billstatus", "I");
            entry.set("qeug_state", state);//付款类型
            entry.set("qeug_paydates", bizDate);//付款日期
            entry.set("qeug_payamount", totalMoney);//付款金额
            qeug_entryentity.add(entry);//付款结果回传记录分录

            SaveServiceHelper.saveOperate(oBill, new DynamicObject[]{Bill}, OperateOption.create());
        }/* else if ("3".equals(state)) {
            //冲销付款
            //冲销付款，清空付款记录，状态变为审核通过，等待手工推送G6
            Bill.set("billstatus", "E");
            Bill.set("qeug_acct_ppe1", null);//清空表头会计科目
            Bill.set("qeug_bank_acc_salary1", null);//清空表头付款账号
            Bill.set("qeug_referencecode", null); //清空参考码
            Bill.set("qeug_istog6", false);//是否已推送G6
            accountEntry.set("oriaccpayedamount", BigDecimal.ZERO);//已付金额变为0
            accountEntry.set("oriaccnotpayamount", oriReceiveAmount);//未付金额变为收款金额
            qeug_entryentity.clear();//清空付款记录分录

            SaveServiceHelper.saveOperate(oBill, new DynamicObject[]{Bill}, OperateOption.create());
        } */else if ("4".equals(state)) {
            //4、部分止付
            if (oriaccpayedamount != null && oriaccpayedamount.compareTo(BigDecimal.ZERO) == 0) {
                //未存在部分付款时，直接将状态变为关闭
                Bill.set("billstatus", "I");
                Bill.set("qeug_stoppayamount", new BigDecimal(totalMoney));//止付金额
                Bill.set("qeug_stoppaydate", new Date());//止付日期
            } else {
                //先调用关闭操作
                OperationServiceHelper.executeOperate("closebill", oBill, new Object[]{String.valueOf(Bill.get("id"))}, operateOption);//调用关闭操作
                //已存在部分付款时，将状态变为部分付款
                Bill.set("billstatus", "J");
                Bill.set("qeug_stoppayamount", new BigDecimal(totalMoney));//止付金额
                Bill.set("qeug_stoppaydate", new Date());//止付日期
            }
            accountEntry.set("oriaccpayedamount", totalMoneyBD.add(oriaccpayedamount));//已付金额=总金额绝对值+已付金额
            BigDecimal oriaccnotpayAmount = oriReceiveAmount.subtract(totalMoneyBD.add(oriaccpayedamount));//收款金额减去已付金额
            accountEntry.set("oriaccnotpayamount", oriaccnotpayAmount);//未付金额
            entry.set("qeug_state", state);//付款类型
            entry.set("qeug_paydates", bizDate);//付款日期
            entry.set("qeug_payamount", totalMoney);//付款金额
            qeug_entryentity.add(entry);//付款结果回传记录分录

            SaveServiceHelper.saveOperate(oBill, new DynamicObject[]{Bill}, OperateOption.create());
        }
        auditApiResultExt.setMessage("推送成功！");
        return auditApiResultExt;
    }

 /*
//     * &#064;description：付款单接口
    @ApiController(value = "SavePaymentOrderController", desc = "金蝶付的款接口，自定义插件")
    public class SavePaymentOrderController implements Serializable {

        private final static Log logger = LogFactory.getLog(SavePaymentOrderController.class);//日志

        private static String oBill = "";//源单标识

        //    private static String pushID= "";//下推规则id
        static CustomApiResult auditApiResultExt = new CustomApiResult();
        private static String tBill = "cas_paybill";//目标单标识

        @ApiPostMapping(value = "/shsh_paymentOrder", desc = "付款单api接口")
        public CustomApiResult<@ApiResponseBody("返回参数") PaymentResultExt> resultExt
                (@NotNull @ApiRequestBody(value = "入参") PaymentModel model) {
            String state = model.getState();//状态
            String sn = model.getSn();//单据号
            auditApiResultExt.setStatus(true);
            //接口日志
            Map<String,Object> log = new HashMap<>();
            log.put("url","G6调用费控");//请求地址
            log.put("user","G6");//登陆信息
            log.put("mode","POST");//请求方式
            // 将 model 对象转换为指定格式的 JSON 字符串
            JSONObject modelJson = new JSONObject();
            modelJson.put("execDate", model.getExecDate());
            modelJson.put("cashamount", model.getCashamount());
            modelJson.put("billamount", model.getBillamount());
            modelJson.put("totalMoney", model.getTotalMoney());
            modelJson.put("lcamount", model.getLcamount());
            modelJson.put("sn", model.getSn());
            modelJson.put("state", model.getState());
            modelJson.put("bankNum", model.getBankNum());
            modelJson.put("referenceCode", model.getReferenceCode());
            log.put("mainstring", modelJson.toJSONString()); // 请求参数
            log.put("operationModule","G6回传接口");//操作模块
            log.put("opdate",new Date());//操作时间
            HashMap<String, Object> auditLog = new HashMap<>();
//        Date date = new Date();
            Date bizDate= null;
            String execDate = String.valueOf(model.getExecDate());//实际付款日期
            SimpleDateFormat inputFormat = new SimpleDateFormat("yyyyMMdd");
            try {
                bizDate = inputFormat.parse(execDate); // 解析为 Date 对象
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
//        auditApiResultExt.setErrorCode("200");
//        1、付款成功;3、付款成功之后做了退票退款冲销，冲销传负值
            if ("1".equals(state) || "3".equals(state)) {
                DynamicObject targetBillObj = pushBill(tBill, model);
                DynamicObject accountBank = BusinessDataServiceHelper.
                        loadSingle("bd_accountbanks", new QFilter("bankaccountnumber", "=", model.getBankNum()).toArray());//在银行账户中查询账户
                if (targetBillObj == null || accountBank == null) {
                    auditApiResultExt.setErrorCode("500");
                    auditApiResultExt.setStatus(false);
                    if (targetBillObj == null) {
                        auditApiResultExt.setMessage("单据号在费控中不存在");
                    } else if (accountBank == null) {
                        auditApiResultExt.setMessage("付款账户在费控中不存在");
                    }
                    // 手动构建日志信息
                    String logMessage = "付款单保存失败: " +
                            "状态码=" + auditApiResultExt.getErrorCode() + ", " +
                            "错误信息=" + auditApiResultExt.getMessage() + ", ";
                    log.put("responsebody", logMessage);//返回参数
                    log.put("pdesc","失败");//操作状态
                    FacadeHelper.apiLog(log);
                    return auditApiResultExt;
                }
                DynamicObjectCollection entry = targetBillObj.getDynamicObjectCollection("entry");
                for (DynamicObject dynamicObject : entry) {
                    dynamicObject.set("e_actamt", 0);
                    dynamicObject.set("e_payableamt", 0);
                }
                targetBillObj.set("bizdate", bizDate); // 业务日期
                targetBillObj.set("qeug_referencecode", model.getReferenceCode()); // 参考码
                OperationResult operationResult = SavePayBill(targetBillObj);//保存下推单据（收款方）
                String message = operationResult.getMessage();
                if(message!=null){
                    auditApiResultExt.setMessage(message);
                    String logMessage = "付款单保存失败: " +
                            "状态码=" + auditApiResultExt.getErrorCode() + ", " +
                            "错误信息=" + auditApiResultExt.getMessage() + ", ";
                    log.put("responsebody", logMessage);//返回参数
                    log.put("pdesc","失败");//操作状态
                    FacadeHelper.apiLog(log);
                    return auditApiResultExt;
                }
                Object pkID = operationResult.getSuccessPkIds().get(0);
                DynamicObject payBill = BusinessDataServiceHelper.loadSingle(pkID, tBill);
                payBill.set("payeracctbank", accountBank);//银行账号
                DynamicObject bank = accountBank.getDynamicObject("bank");
//            DynamicObject bank = BusinessDataServiceHelper.loadSingle(bankId,"bd_accountbanks");
                payBill.set("payerbank", bank);//付款银行
                DynamicObjectCollection billEntry = payBill.getDynamicObjectCollection("entry");//付款明细分录
                BigDecimal totalPayment = BigDecimal.ZERO;//付款金额
                BigDecimal totalMoney = BigDecimal.ZERO;//总金额
//            1、付款成功
                if ("1".equals(state)) {
                    if (billEntry.size() > 0) {//判断分录是否为多行
                        totalMoney = new BigDecimal(model.getTotalMoney());
                        BigDecimal divide = totalMoney.divide(BigDecimal.valueOf(billEntry.size()),2, RoundingMode.HALF_UP);//总金额除总行数
                        if (totalMoney.remainder(new BigDecimal(billEntry.size())).compareTo(new BigDecimal(0)) == 0) {//判断是否可以整除
                            for (int i = 0; i < billEntry.size(); i++) {
                                billEntry.get(i).set("e_actamt", divide);
                                billEntry.get(i).set("e_unsettledlocalamt", divide);
                                billEntry.get(i).set("e_unlockamt", divide);
                                billEntry.get(i).set("e_unsettledamt", divide);
                                billEntry.get(i).set("e_payableamt", divide);
                                billEntry.get(i).set("e_payablelocamt", divide);
                                billEntry.get(i).set("e_localamt", divide);
                            }
                        }else {//若不能整除
                            for (int i = 0; i < billEntry.size(); i++) {
                                if (i + 1 == billEntry.size()) {//循环最后一行，则取最后一行的值
                                    BigDecimal negate = totalMoney.subtract(totalPayment);
                                    billEntry.get(i).set("e_actamt", negate);
                                    billEntry.get(i).set("e_unsettledlocalamt", negate);
                                    billEntry.get(i).set("e_unlockamt", negate);
                                    billEntry.get(i).set("e_unsettledamt", negate);
                                    billEntry.get(i).set("e_payableamt", negate);
                                    billEntry.get(i).set("e_payablelocamt", negate);
                                    billEntry.get(i).set("e_localamt", negate);
                                } else {
                                    billEntry.get(i).set("e_actamt", divide);
                                    billEntry.get(i).set("e_unsettledlocalamt", divide);
                                    billEntry.get(i).set("e_unlockamt", divide);
                                    billEntry.get(i).set("e_unsettledamt", divide);
                                    billEntry.get(i).set("e_payableamt", divide);
                                    billEntry.get(i).set("e_payablelocamt", divide);
                                    billEntry.get(i).set("e_localamt", divide);
                                    totalPayment = totalPayment.add(divide);
                                }
                            }
                        }
                    }
                }
//            3、付款成功之后做了退票退款冲销，冲销传负值
                else if ("3".equals(state)) {
                    if (billEntry.size() > 0) {//判断分录是否为多行
                        totalMoney = new BigDecimal(model.getTotalMoney());
                        BigDecimal divide = totalMoney.divide(BigDecimal.valueOf(billEntry.size()),2, RoundingMode.HALF_UP);//总金额除总行数//通过将 totalMoney 除以账单条目的数量（billEntry.size()）得到平均值
                        if (totalMoney.remainder(new BigDecimal(billEntry.size())).compareTo(new BigDecimal(0)) == 0) {//判断是否可以整除，计算 totalMoney 除以账单条目的数量（billEntry.size()）的余数
                            for (int i = 0; i < billEntry.size(); i++) {
                                billEntry.get(i).set("e_actamt", divide.abs().negate());
                                billEntry.get(i).set("e_unsettledlocalamt", divide.abs().negate());
                                billEntry.get(i).set("e_unlockamt", divide.abs().negate());
                                billEntry.get(i).set("e_unsettledamt", divide.abs().negate());
                                billEntry.get(i).set("e_payableamt", divide.abs().negate());
                                billEntry.get(i).set("e_payablelocamt", divide.abs().negate());
                                billEntry.get(i).set("e_localamt", divide.abs().negate());
//                            totalPayment = totalPayment.add(divide.abs().negate());
                            }
                        } else {//若不能整除
                            for (int i = 0; i < billEntry.size(); i++) {
                                if (i + 1 == billEntry.size()) {//循环最后一行，则取最后一行的值
//                                BigDecimal multiply = divide.multiply(new BigDecimal(billEntry.size()));//平均值乘行数
                                    BigDecimal negate = totalMoney.subtract(totalPayment).abs().negate();
                                    billEntry.get(i).set("e_actamt", negate);
                                    billEntry.get(i).set("e_unsettledlocalamt", negate);
                                    billEntry.get(i).set("e_unlockamt", negate);
                                    billEntry.get(i).set("e_unsettledamt", negate);
                                    billEntry.get(i).set("e_payableamt", negate);
                                    billEntry.get(i).set("e_payablelocamt", negate);
                                    billEntry.get(i).set("e_localamt", negate);
//                                totalPayment = totalPayment.add(totalMoney.subtract(multiply).abs().negate());
                                } else {
                                    billEntry.get(i).set("e_actamt", divide.abs().negate());
                                    billEntry.get(i).set("e_unsettledlocalamt", divide.abs().negate());
                                    billEntry.get(i).set("e_unlockamt", divide.abs().negate());
                                    billEntry.get(i).set("e_unsettledamt", divide.abs().negate());
                                    billEntry.get(i).set("e_payableamt", divide.abs().negate());
                                    billEntry.get(i).set("e_payablelocamt", divide.abs().negate());
                                    billEntry.get(i).set("e_localamt", divide.abs().negate());
                                    totalPayment = totalPayment.add(divide.abs().negate());
                                }
                            }
                        }
                    }
                }
                payBill.set("actpayamt", model.getTotalMoney());
                payBill.set("localamt", model.getTotalMoney());
                payBill.set("billstatus", "C");
                payBill.set("bizdate",bizDate);//业务日期
                targetBillObj.set("qeug_referencecode", model.getReferenceCode()); // 参考码
//            payBill.set("entry",billEntry);
                OperationResult payBill1Result = SavePayBill(payBill);
                String saveMessage = saveMessage(payBill1Result);//保存结果
                if (saveMessage.equals("")) {
                    //操作日志记录
                    auditLog.put("billno", sn);
                    if ("1".equals(state)) {
                        auditLog.put("type", "付款成功");
                    }else if ("3".equals(state)) {
                        auditLog.put("type", "付款成功之后做了退票退款冲销，冲销传负值");
                    }
                    auditLog.put("date", bizDate);
                    auditLog.put("amount", totalMoney);
                    FacadeHelper.logPayment(auditLog);
                    auditApiResultExt.setMessage("推送成功！");
                } else {
                    auditApiResultExt.setMessage(saveMessage);
                    auditApiResultExt.setErrorCode("500");
                    auditApiResultExt.setStatus(false);
                    // 手动构建日志信息
                    String logMessage = "付款单保存失败: " +
                            "状态码=" + auditApiResultExt.getErrorCode() + ", " +
                            "错误信息=" + auditApiResultExt.getMessage() + ", ";
                    log.put("responsebody", logMessage);//返回参数
                    log.put("pdesc","失败");//操作状态
                    FacadeHelper.apiLog(log);
                    return auditApiResultExt;
                }
            }// 2、终止付款
            else if ("2".equals(state)) {
                DynamicObject dynamicObject = getBillType(sn);
                if (dynamicObject == null) {
                    auditApiResultExt.setMessage("单据号在费控中不存在");
                    auditApiResultExt.setErrorCode("500");
                    auditApiResultExt.setStatus(false);
                    // 手动构建日志信息
                    String logMessage = "付款单保存失败: " +
                            "状态码=" + auditApiResultExt.getErrorCode() + ", " +
                            "错误信息=" + auditApiResultExt.getMessage() + ", ";
                    log.put("responsebody", logMessage);//返回参数
                    log.put("pdesc","失败");//操作状态
                    FacadeHelper.apiLog(log);
                    return auditApiResultExt;
                }
                dynamicObject.set("billstatus", "I");
                OperationResult saveResult = SaveServiceHelper.saveOperate(oBill, new DynamicObject[]{dynamicObject});
                String saveMessage = saveMessage(saveResult);
                if (saveMessage.equals("")) {
                    //操作日志记录
                    auditLog.put("billno", sn);
                    auditLog.put("type", "终止付款");
                    auditLog.put("date", bizDate);
                    auditLog.put("amount", "");
                    FacadeHelper.logPayment(auditLog);
                    auditApiResultExt.setMessage("推送成功！");
                } else {
                    auditApiResultExt.setMessage(saveMessage);
                    auditApiResultExt.setErrorCode("500");
                    auditApiResultExt.setStatus(false);
                    // 手动构建日志信息
                    String logMessage = "付款单保存失败: " +
                            "状态码=" + auditApiResultExt.getErrorCode() + ", " +
                            "错误信息=" + auditApiResultExt.getMessage() + ", ";
                    log.put("responsebody", logMessage);//返回参数
                    log.put("pdesc","失败");//操作状态
                    FacadeHelper.apiLog(log);
                    return auditApiResultExt;
                }
            }//4、部分止付
            else if ("4".equals(state)) {
                DynamicObject dynamicObject = getBillType(sn);
                if (dynamicObject == null) {
                    auditApiResultExt.setMessage("单据号在费控中不存在");
                    auditApiResultExt.setErrorCode("500");
                    auditApiResultExt.setStatus(false);
                    // 手动构建日志信息
                    String logMessage = "付款单保存失败: " +
                            "状态码=" + auditApiResultExt.getErrorCode() + ", " +
                            "错误信息=" + auditApiResultExt.getMessage() + ", ";
                    log.put("responsebody", logMessage);//返回参数
                    log.put("pdesc","失败");//操作状态
                    FacadeHelper.apiLog(log);
                    return auditApiResultExt;
                }
                dynamicObject.set("billstatus", "I");
                dynamicObject.set("qeug_stoppayamount", new BigDecimal(model.getTotalMoney()));//dynamicObject.getDynamicObject("notpayamount")
                dynamicObject.set("qeug_stoppaydate", new Date());
                OperationResult saveResult = SaveServiceHelper.saveOperate(oBill, new DynamicObject[]{dynamicObject});
                String saveMessage = saveMessage(saveResult);
                if (saveMessage.equals("")) {
                    //操作日志记录
                    auditLog.put("billno", sn);
                    auditLog.put("type", "部分止付");
                    auditLog.put("date", bizDate);
                    auditLog.put("amount", new BigDecimal(model.getTotalMoney()));
                    FacadeHelper.logPayment(auditLog);
                    auditApiResultExt.setMessage("推送成功！");
                } else {
                    auditApiResultExt.setMessage(saveMessage);
                    auditApiResultExt.setErrorCode("500");
                    auditApiResultExt.setStatus(false);
                    // 手动构建日志信息
                    String logMessage = "付款单保存失败: " +
                            "状态码=" + auditApiResultExt.getErrorCode() + ", " +
                            "错误信息=" + auditApiResultExt.getMessage() + ", ";
                    log.put("responsebody", logMessage);//返回参数
                    log.put("pdesc","失败");//操作状态
                    FacadeHelper.apiLog(log);
                    return auditApiResultExt;
                }
            } else {
                auditApiResultExt.setMessage("state状态值未知！");
                auditApiResultExt.setErrorCode("500");
                auditApiResultExt.setStatus(false);
                // 手动构建日志信息
                String logMessage = "付款单保存失败: " +
                        "状态码=" + auditApiResultExt.getErrorCode() + ", " +
                        "错误信息=" + auditApiResultExt.getMessage() + ", ";
                log.put("responsebody", logMessage);//返回参数
                log.put("pdesc","失败");//操作状态
                FacadeHelper.apiLog(log);
                return auditApiResultExt;
            }
            // 手动构建日志信息
            String logMessage = "付款单保存成功: " +
                    "状态码=" + auditApiResultExt.getErrorCode() + ", " +
                    "信息=" + auditApiResultExt.getMessage() + ", ";
            log.put("responsebody", logMessage);//返回参数
            log.put("pdesc","成功");//操作状态
            FacadeHelper.apiLog(log);
            return auditApiResultExt;
        }*/

    /**
     * 判断是哪张单据
     *
     * @param sn 单据号
     * @return 单据
     */
    public static DynamicObject getBillType(String sn) {
        oBill = "er_dailyreimbursebill";//费用报销单
        DynamicObject dynamicObject = BusinessDataServiceHelper.loadSingle(oBill, new QFilter("billno", "=", sn).toArray());
        if (dynamicObject == null) {
            dynamicObject = BusinessDataServiceHelper.loadSingle("er_dailyloanbill", new QFilter("billno", "=", sn).toArray());
            oBill = "er_dailyloanbill";//借款单
        }
        if (dynamicObject == null) {
            dynamicObject = BusinessDataServiceHelper.loadSingle("er_tripreimbursebill", new QFilter("billno", "=", sn).toArray());
            oBill = "er_tripreimbursebill";//差旅报销单
        }
        if (dynamicObject == null) {
            dynamicObject = BusinessDataServiceHelper.loadSingle("er_publicreimbursebill", new QFilter("billno", "=", sn).toArray());
            oBill = "er_publicreimbursebill";//付款申请（对公报销
        }
        return dynamicObject;
    }
}
